package com.ocean.array;

import java.util.Arrays;

/**
 * https://leetcode.cn/problems/rotate-array/
 */
public class RotateArray2 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7};
        System.out.println(Arrays.toString(nums));
        new RotateArray2().rotate(nums, 2);
        System.out.println(Arrays.toString(nums));
    }


    public void rotate(int[] nums, int k) {
        // 将原来的数组全部反转
        if (nums == null || nums.length <= 1) {
            return;
        }
        reverse(nums, 0, nums.length - 1);
        reverse(nums, 0, k - 1);
        reverse(nums, k, nums.length - 1);
    }

    public void rotate2(int[] nums, int k) {
        // 创建一个新的数组 把原来的数组放到新的数组里面
        if (nums == null || nums.length <= 1) {
            return;
        }
        int n = nums.length;
        int[] newNums = new int[n];
        for (int i = 0; i < n; i++) {
            newNums[(i + k) % n] = nums[i];
        }
        System.arraycopy(newNums, 0, nums, 0, n);
    }

    private void reverse(int[] num, int start, int end) {
        while (start < end) {
            int temp = num[start];
            num[start] = num[end];
            num[end] = temp;
            start++;
            end--;
        }
    }

}
